import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:macless_haystack/accessory/accessory_model.dart';
import 'package:share_plus/share_plus.dart';
import 'package:universal_html/html.dart' as html;
import 'package:path_provider/path_provider.dart';

class GPXPoint {
  final double latitude;
  final double longitude;
  final DateTime? time;

  GPXPoint({
    required this.latitude,
    required this.longitude,
    this.time,
  });
}

class GPXHelper {
  /// 生成GPX文件内容（仅包含轨迹部分）
  static String generateGPX(List<Pair<dynamic, dynamic>> points) {
    final buffer = StringBuffer();

    // 开始写入XML
    buffer.write('<?xml version="1.0" encoding="UTF-8"?>\n');
    buffer.write('<gpx version="1.1" creator="Macless Haystack GPX Generator">\n');

    // 开始轨迹
    buffer.write('  <trk>\n');

    // 创建轨道段
    buffer.write('    <trkseg>\n');

    // 写入所有轨迹点
    for (final point in points) {
      buffer.write('      <trkpt lat="${point.location.latitude}" lon="${point.location.longitude}">\n');
      // 如果有时间信息
      buffer.write('        <time>${_formatDateTime(point.start!)}</time>\n');

      buffer.write('      </trkpt>\n');
    }

    // 结束轨道段
    buffer.write('    </trkseg>\n');

    // 结束轨迹
    buffer.write('  </trk>\n');

    // 结束GPX根元素
    buffer.write('</gpx>');

    return buffer.toString();
  }

  // 格式化日期时间为ISO8601格式
  static String _formatDateTime(DateTime dateTime) {
    // 确保时区为UTC并添加Z标识
    return dateTime.toUtc().toIso8601String();
  }

  static Future<void> export(String filename, List<Pair<dynamic, dynamic>> points) async {
    String encodedAccessories = generateGPX(points);

    if (kIsWeb) {
      final blob =
          html.Blob([encodedAccessories], 'application/json', 'native');
      final url = html.Url.createObjectUrlFromBlob(blob);

      html.AnchorElement(href: url)
        ..setAttribute('download', filename)
        ..click();

      html.Url.revokeObjectUrl(url);
    } else {
      // Create temporary directory to store export file
      Directory tempDir = await getTemporaryDirectory();
      String path = tempDir.path;

      // Create file and write accessories as json

      File file = File('$path/$filename');

      await file.writeAsString(encodedAccessories);
      // Share export file over os share dialog

      Share.shareXFiles(
        [XFile(file.path)],
        subject: filename,
      );
    }
  }
}
